if (!window.PassDataComponent) {
  class PassDataComponent {
    constructor(containerId = 'content') {
      this.container = document.getElementById(containerId);
        this.template = null;
      this.init();
    }
  
    async init() {
      await this.loadTemplate();
      this.renderSkeleton();
      this.renderData(); // 加载数据并渲染
      this.bindEvents();
    }
  
    async loadTemplate() {
      const response = await fetch('/static/templates/passdata-template.html');
      this.template = await response.text();
    }
  
    async renderData() {
      const datas = await this.fetchData();
      const dataList = this.dataContainer.querySelector('.data-list');
      dataList.innerHTML = datas.map(data => 
        `<div class="pass-data-entry">
          <span>${data[2]}</span>
          <span>${new Date(data[5]).toLocaleString()}</span>
          <span class="type-tag ${(data[3] || '').toLowerCase()}">${data[3] || ''}</span>
        </div>`
      ).join('');
      // const tbody = this.dataContainer.querySelector('.data-body');
      // const thead = this.dataContainer.querySelector('.column-headers');
      
      // // 渲染表头
      // thead.innerHTML = ['ID', '姓名', '性别', '国籍', '上个计时点', '本点位时间', '与第一名差', '分段时间', '预计完赛', '公里类型', '名次', '备注']
      //   .map((text, index) => `<th data-col="${index}">${text}</th>`).join('');
  
      // // 渲染表格数据
      // tbody.innerHTML = datas.map(data => 
      //   `<tr>
      //     <td>${data.serial}</td>
      //     <td>${data.name}</td>
      //     <td>${data.gender}</td>
      //     <td>${data.nationality}</td>
      //     <td>${data.previousCheckpoint}</td>
      //     <td class="selected-column">${data.currentCheckpoint}</td>
      //     <td>${data.timeDifference}</td>
      //     <td>${data.segmentPace}</td>
      //     <td>${data.estimatedFinish}</td>
      //     <td>${data.kmType}km</td>
      //     <td>${data.ranking}</td>
      //     <td>${data.remark}</td>
      //   </tr>`
      // ).join('');
      
      // // 默认选中第五列（索引4）
      // this.setSelectedColumn(4);
    }
  
    renderSkeleton() {
      if (!this.container) {
        console.error('Container not initialized');
        return;
      }
      this.container.innerHTML = this.template;
      this.dataContainer = this.container.querySelector('.passdata-container');
      this.searchBox = this.container.querySelector('.search-input');
      this.filterButtons = this.container.querySelectorAll('.filter-btn');
      this.kmSelect = this.container.querySelector('.km-select');
    }
  
    renderDataCSV(datas) {
      
      const tbody = this.dataContainer.querySelector('.data-body');
      const thead = this.dataContainer.querySelector('.column-headers');
      
      // 渲染表头
      thead.innerHTML = ['ID', '姓名', '性别', '国籍', '上个计时点', '本点位时间', '与第一名差', '分段时间', '预计完赛', '公里类型', '名次', '备注']
        .map((text, index) => `<th data-col="${index}">${text}</th>`).join('');
  
      // 渲染表格数据
      tbody.innerHTML = datas.map(data => 
        `<tr>
          <td>${data.serial}</td>
          <td>${data.name}</td>
          <td>${data.gender}</td>
          <td>${data.nationality}</td>
          <td>${data.previousCheckpoint}</td>
          <td class="selected-column">${data.currentCheckpoint}</td>
          <td>${data.timeDifference}</td>
          <td>${data.segmentPace}</td>
          <td>${data.estimatedFinish}</td>
          <td>${data.kmType}km</td>
          <td>${data.ranking}</td>
          <td>${data.remark}</td>
        </tr>`
      ).join('');
      
      // 默认选中第五列（索引4）
      this.setSelectedColumn(4);
    }
  
    setSelectedColumn(colIndex) {
      document.querySelectorAll('.selected-column').forEach(el => el.classList.remove('selected-column'));
      document.querySelectorAll(`td:nth-child(${colIndex + 1}), th:nth-child(${colIndex + 1})`)
        .forEach(el => el.classList.add('selected-column'));
    }
  
    async fetchData() {
      const response = await fetch('/api/passResult');
      return response.json();
    }
  
    bindEvents() {
      this.searchBox.addEventListener('input', this.handleSearch.bind(this));
      this.filterButtons.forEach(btn => {
        btn.addEventListener('click', this.handleFilter.bind(this));
      });
  
      // 表格列点击事件
      this.dataContainer.querySelector('.column-headers').addEventListener('click', (e) => {
        if (e.target.tagName === 'TH') {
          const colIndex = parseInt(e.target.dataset.col);
          this.setSelectedColumn(colIndex);
        }
      });
  
      document.querySelector('.chart-btn')?.addEventListener('click', () => {
        console.log('Chart button clicked'); // 这里可以添加图表显示逻辑
      });
      // 导入按钮事件
      document.querySelector('.import-btn')?.addEventListener('click', () => {
        document.querySelector('.csv-upload').click();
      });
  
      // 容器委托事件
      document.querySelector('.passdata-container')?.addEventListener('click', (e) => {
        if (e.target.classList.contains('import-btn')) {
          const fileInput = document.querySelector('.csv-upload');
          fileInput.dataset.kmType = this.kmSelect.value;
          fileInput.click();
        }
      }, { once: true });
  
      // 文件上传事件
      this.container.querySelector('.csv-upload')?.addEventListener('change', (e) => {
        this.handleFileUpload(e);
      }, { once: true });
      // 延迟绑定确保表格已渲染
  setTimeout(() => {
    this.container.querySelector('.submitPassData-btn')?.addEventListener('click', async () => {
        const table = this.dataContainer.querySelector('.passdata-table');
        if (!table) throw new Error('表格元素未找到');
        const kmType = this.kmSelect.value;
        const colIndex = parseInt(this.dataContainer.querySelector('th.selected-column')?.dataset.col || 4);
        const rows = Array.from(table.rows).slice(1); // 跳过表头
    
        const params = rows.map(row => {
          const cells = row.cells;
          return {
            datatype: {
              '42': 42,
              '40': 40,
              '35': 35,
              '30': 30,
              '25': 25,
              '20': 20,
              '15': 15,
              '10': 10,
              '5': 5,
              '0': 0
            }[kmType] || 0, // 添加默认值防止undefined // 添加默认值防止undefined
            playerId: cells[0].textContent,
            name: cells[1].textContent,
            time: cells[colIndex]?.textContent || '',
            country: cells[3].textContent,
            gender: cells[2].textContent === '男' ? 1 : cells[2].textContent === '女' ? 0 : 0,
          };
        });
        console.log(params);
        try {
          const response = await fetch('/api/submit-pass-result', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(params)
          });
          
          if (response.ok) {
            alert('数据提交成功！');
          } else {
            alert(`提交失败: ${await response.text()}`);
          }
        } catch (error) {
          console.error('提交错误:', error);
          alert('网络请求失败');
        }
      });
    }, 100);
    }
  
    handleSearch(e) {
      // 搜索功能实现
    }
  
    handleFilter(e) {
      // 过滤功能实现
    }
  
    handleFileUpload(e) {
      const file = e.target.files[0];
      if (!file) return;
  
      const reader = new FileReader();
      reader.onload = (event) => {
        try {
          const csvData = this.parseCSV(event.target.result);
          this.renderDataCSV(csvData);
          alert(`成功导入${file.name}，共${csvData.length}条数据`);
        } catch (error) {
          console.error('CSV解析失败:', error);
          alert(`导入失败: ${error.message}`);
        }
      };
      reader.readAsText(file);
    }
  
    parseCSV(csvText) {
      const kmType = this.kmSelect?.value || '本地数据';
  
      const lines = csvText.split('\n').filter(line => line.trim());
      if (lines.length < 1) throw new Error('CSV文件内容为空');
  
      return lines.map(line => {
        const fields = line.split(';').map(f => f.trim());
        if (fields.length < 16) throw new Error('CSV字段数量不足');
  
        // 必填字段校验
        if (!fields[0] || !fields[1] || !fields[4]) {
          throw new Error('缺失必填字段（ID/姓名/时间）');
        }
  
        return {
          serial: fields[0],
          name: fields[1],
          gender: fields[2] || '男',
          nationality: fields[3] || '未知',
          previousCheckpoint: this.convertTimeFormat(fields[4]),  // 上个计时点时间
          currentCheckpoint: this.convertTimeFormat(fields[5]),   // 本点位时间
          timeDifference: fields[13] || '+0:00:00',               // 与第一名时间差
          segmentPace: fields[14],                                // 分段时间
          estimatedFinish: this.convertTimeFormat(fields[15]),    // 预计完赛时间
          kmType: kmType,
          ranking: parseInt(fields[16]) || 0,                     // 当前点位名次
          remark: fields[12] || ''
        };
      });
    }
  
    convertTimeFormat(timeStr) {
      if (!timeStr) return '--:--:--';
      
      try {
        // 处理带+号的时间差
        if (timeStr.startsWith('+')) {
          return timeStr;
        }
        
        const [h, m, s] = timeStr.split(':');
        
        if (/^\d{2}:\d{2}:\d{2}$/.test(timeStr)) {
          return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
        }
        
        throw new Error('无效时间格式');
      } catch (e) {
        throw new Error(`无效时间格式: ${timeStr}`);
      }
    }
  
    async uploadCSVData(csvData) {
      // 保持原有上传逻辑
    }
  }
  
  window.PassDataComponent = PassDataComponent;
  }
  